package com.itheima.binarysearch;

public class BinarySearchBalance {
    public static void main(String[] args) {
        int[] arr = {3,6,7,9,10,15,19,28,31,40};
        System.out.println(binarySearch(arr, 40));


    }

    /*public static int binarySearchBalance(int[] a, int target) {
        int i = 0, j = a.length;
        while (1 < j - i) {
            int m = (i + j) >>> 1;
            if (target < a[m]) {
                j = m;
            } else {
                i = m;
            }
        }
        return (a[i] == target) ? i : -1;
    }*/

    public static int binarySearch(int[] arr, int target) {
        int i = 0, j = arr.length;
        while (1 < j - i) {          //确定在要查找的范围中还有几个元素
            int m = (i + j) >>> 1;
            if (target < arr[m]) {
                j = m;
            } else {
                i = m;              //这种情况目标值包含大于中间值和等于中间值
            }
        }
        if (target == arr[i]) {
            return i;
        } else {
            return -1;
        }
    }
}
